package com.lxy.mychat.ui.Contact;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.lxy.mychat.Adapter.UserAdapter;
import com.lxy.mychat.Bean.User;
import com.lxy.mychat.ChatActivity;
import com.lxy.mychat.R;

import org.litepal.LitePal;

import java.util.List;

public class ContactFragment extends Fragment {
    private ListView lv;
    UserAdapter adapter;
    List<User> userList;
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_contact, container, false);
        initView(root);
        setListener();
        return root;
    }

    private void setListener() {
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                User u=userList.get(position);
                Intent intent=new Intent(getContext(), ChatActivity.class);
                intent.putExtra("receivename",u.getName());
                intent.putExtra("receiveid",u.getId());
                startActivity(intent);
            }
        });
    }

    private void initView(View root) {
        SharedPreferences sp=getActivity().getSharedPreferences("userinfo", Context.MODE_PRIVATE);
        userList=LitePal.where("id != ?",sp.getInt("userid",-1)+"").find(User.class);
        lv=root.findViewById(R.id.lv);
        adapter=new UserAdapter(getContext(),R.layout.user_item,userList);
        lv.setAdapter(adapter);
    }
}